<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="UTF-8">
  <title>Ptgb 详情</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    /* 响应式基础设置 */
    body {
      margin: 0;
      padding: 0;
      font-family: sans-serif;
      line-height: 1.5;
    }
    .container {
      max-width: 800px;
      margin: 0 auto;
      padding: 16px;
    }
    .ptgb-info {
      margin-bottom: 20px;
      border: 1px solid #ccc;
      padding: 16px;
      border-radius: 6px;
    }
    .ptgb-info h2 {
      margin-top: 0;
      text-align: center;
    }
    .ptgb-info table {
      width: 100%;
      border-collapse: collapse;
    }
    .ptgb-info th, .ptgb-info td {
      text-align: left;
      padding: 6px;
      border-bottom: 1px solid #eaeaea;
      word-break: break-all;
    }
    /* 图片展示区域 */
    .images-section {
      margin-top: 20px;
    }
    .images-list {
      display: flex;
      flex-direction: column; /* 使图片垂直排布，方便上下移 */
      gap: 8px;
      margin-bottom: 12px;
    }
    .image-item {
      position: relative;
      display: flex;
      align-items: center;
      border: 1px solid #eee;
      padding: 4px;
    }
    .image-item img {
      width: 120px;
      height: 120px;
      object-fit: cover; /* 避免变形 */
    }
    .image-controls {
      display: flex;
      flex-direction: column;
      gap: 4px;
      margin-left: 8px;
    }
    .controls-btn {
      padding: 4px 8px;
      font-size: 12px;
      border: none;
      border-radius: 3px;
      cursor: pointer;
      background-color: #ddd;
      color: #000;
      min-width: 45px;
      text-align: center;
    }
    .controls-btn:hover {
      opacity: 0.8;
    }
    .delete-button {
      position: absolute;
      top: 2px;
      right: 2px;
      background: rgba(255, 0, 0, 0.7);
      color: #fff;
      border: none;
      cursor: pointer;
      font-size: 12px;
      border-radius: 3px;
    }
    /* 上传按钮样式 */
    .upload-section {
      margin-top: 20px;
      padding: 12px;
      border: 1px solid #ccc;
      border-radius: 6px;
    }
    .btn {
      display: inline-block;
      padding: 6px 12px;
      background-color: #007bff;
      color: #fff;
      font-size: 14px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      text-decoration: none;
    }
    .btn:hover {
      opacity: 0.9;
    }
    .hidden {
      display: none;
    }
    .drag-tip {
      font-size: 0.85em;
      color: #888;
    }
  </style>
</head>
<body>
<div class="container">

  <!-- Ptgb 信息展示 -->
  <div class="ptgb-info">
    <table>
      <tr>
        <th>医保码</th>
        <td>{{ ptgb.ybm }}</td>
      </tr>
      <tr>
        <th>奇安码</th>
        <td>{{ ptgb.pta25 }}</td>
      </tr>
      <tr>
        <th>通用名称</th>
        <td>{{ ptgb.a2 }}</td>
      </tr>
      <tr>
        <th>生产企业</th>
        <td>{{ ptgb.a8 }}</td>
      </tr>
      <tr>
        <th>规格</th>
        <td>{{ ptgb.a9 }}</td>
      </tr>
      <tr>
        <th>批准文号</th>
        <td>{{ ptgb.a29 }}</td>
      </tr>
      <tr>
        <th>条形码</th>
        <td>{{ ptgb.a40 }}</td>
      </tr>
      <tr>
        <th>追溯码</th>
        <td>{{ ptgb.spbsm }}</td>
      </tr>
    </table>
  </div>

  <!-- 图片展示区域 -->
  <div class="images-section">
    <h3>图片展示</h3>
    <div class="images-list" id="imagesList">
      {% for pic in existing_pics %}
        <div class="image-item" data-image-path="{{ pic }}" id="imageItem{{ forloop.counter }}">
          <a href="{{ MEDIA_URL }}{{ pic }}"><img src="{{ MEDIA_URL }}{{ pic }}" alt="Img"></a>
          <button class="delete-button" onclick="deleteImage('{{ pic }}', {{ ptgb.pta25 }})">删除</button>
          <!— 上/下移动按钮 —>
          <div class="image-controls">
            <button class="controls-btn" onclick="moveUp('{{ forloop.counter }}')">↑ 上移</button>
            <button class="controls-btn" onclick="moveDown('{{ forloop.counter }}')">↓ 下移</button>
          </div>
        </div>
      {% empty %}
        暂无图片。
      {% endfor %}
    </div>
    <button class="btn" style="margin-top: 12px;" onclick="saveOrder({{ ptgb.pta25 }})">保存顺序</button>
  </div>

  <!-- 上传图片区域：仅保留一个“拍照/上传图片”按钮，自动居中裁剪为800*800，压缩到300k以内 -->
  <div class="upload-section">
    <h3>上传图片</h3>
    <input id="hiddenFileInput" type="file" accept="image/*" capture="camera" style="display:none">
    <button class="btn" onclick="handleFileSelect({{ ptgb.pta25 }})">拍照/上传图片</button>
  </div>

</div>

<script>
  // ============== 删除图片 ==============
  function deleteImage(imagePath, ptgbId) {
    if (!confirm('是否确定删除该图片？')) return;

    const formData = new FormData();
    formData.append('image_path', imagePath);

    fetch(`/delete_image/${ptgbId}/`, {
      method: 'POST',
      headers: {
        'X-CSRFToken': '{{ csrf_token }}'
      },
      body: formData
    })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        alert('删除成功');
        location.reload(); // 或者从DOM中移除该图片元素
      } else {
        alert(data.message);
      }
    })
    .catch(err => {
      console.error(err);
      alert('删除请求失败');
    });
  }

  // ============== 上/下按钮移动图片顺序 ==============
  // 通过 DOM 操作改变元素位置
  function moveUp(counter) {
    const currentElem = document.getElementById('imageItem' + counter);
    if (!currentElem) return;

    const prevElem = currentElem.previousElementSibling;
    if (prevElem) {
      currentElem.parentNode.insertBefore(currentElem, prevElem);
    }
  }

  function moveDown(counter) {
    const currentElem = document.getElementById('imageItem' + counter);
    if (!currentElem) return;

    const nextElem = currentElem.nextElementSibling;
    if (nextElem) {
      currentElem.parentNode.insertBefore(nextElem, currentElem);
    }
  }

  // 保存新的顺序
  function saveOrder(ptgbId) {
    const listContainer = document.getElementById('imagesList');
    const itemElems = listContainer.querySelectorAll('.image-item');
    const formData = new FormData();

    itemElems.forEach(elem => {
      formData.append('ordered_pics[]', elem.dataset.imagePath);
    });

    fetch(`/reorder_images/${ptgbId}/`, {
      method: 'POST',
      headers: {
        'X-CSRFToken': '{{ csrf_token }}'
      },
      body: formData
    })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        alert(data.message || '图片顺序更新成功');
      } else {
        alert(data.message || '更新失败');
      }
    })
    .catch(err => {
      console.error(err);
      alert('请求失败');
    });
  }

  // ============== 拍照/上传后自动居中裁剪 800*800 并压缩到 300KB 以内 ==============
  function handleFileSelect(ptgbId) {
    const fileInput = document.getElementById('hiddenFileInput');
    fileInput.value = ''; // 重置，以便可重复触发同一文件
    fileInput.click();

    fileInput.onchange = async function() {
      const file = fileInput.files[0];
      if (!file) return;

      // 检查类型
      const validTypes = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif'];
      if (!validTypes.includes(file.type)) {
        alert('不支持的文件类型');
        return;
      }
      // 读取并绘制到 canvas
      try {
        const croppedBlob = await cropAndCompressImage(file, 1500, 1500, 1000 * 1024);
        // 上传到服务器
        uploadCroppedImage(ptgbId, croppedBlob);
      } catch (e) {
        console.error(e);
        alert('图片处理失败');
      }
    };
  }

  /**
   * 自动居中裁剪到固定宽高，然后压缩到指定大小以内
   * @param {File} imageFile 原始图片文件
   * @param {number} targetWidth 目标宽度，如 1000
   * @param {number} targetHeight 目标高度，如 1000
   * @param {number} sizeLimit 最终目标大小（字节），如 500 * 1024
   * @returns {Promise<Blob>} 返回裁剪、压缩后的 Blob
   */
  function cropAndCompressImage(imageFile, targetWidth, targetHeight, sizeLimit) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = function(e) {
        const img = new Image();
        img.onload = function() {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');

          // 计算居中裁剪区域
          const originWidth = img.width;
          const originHeight = img.height;
          const aspectTarget = targetWidth / targetHeight;
          const aspectOriginal = originWidth / originHeight;

          let sWidth, sHeight, sx, sy;
          if (aspectOriginal > aspectTarget) {
            // 以高度为基准裁剪宽度
            sHeight = originHeight;
            sWidth = Math.floor(sHeight * aspectTarget);
            sx = Math.floor((originWidth - sWidth) / 2);
            sy = 0;
          } else {
            // 以宽度为基准裁剪高度
            sWidth = originWidth;
            sHeight = Math.floor(sWidth / aspectTarget);
            sx = 0;
            sy = Math.floor((originHeight - sHeight) / 2);
          }

          canvas.width = targetWidth;
          canvas.height = targetHeight;
          ctx.drawImage(img, sx, sy, sWidth, sHeight, 0, 0, targetWidth, targetHeight);

          // 压缩
          let quality = 1.0;
          function tryCompress() {
            const dataURL = canvas.toDataURL('image/jpeg', quality);
            // 转为Blob
            const byteString = atob(dataURL.split(',')[1]);
            const buffer = new ArrayBuffer(byteString.length);
            const view = new Uint8Array(buffer);
            for (let i = 0; i < byteString.length; i++) {
              view[i] = byteString.charCodeAt(i);
            }
            const blob = new Blob([buffer], { type: 'image/jpeg' });

            if (blob.size <= sizeLimit || quality <= 0.05) {
              resolve(blob);
            } else {
              quality -= 0.05;
              tryCompress();
            }
          }
          tryCompress();
        };
        img.onerror = reject;
        img.src = e.target.result;
      };
      reader.onerror = reject;
      reader.readAsDataURL(imageFile);
    });
  }

  // 将处理后的 Blob 通过表单形式上传
  function uploadCroppedImage(ptgbId, croppedBlob) {
    const formData = new FormData();
    // 后端视图是按 "images" 获取
    formData.append('images', croppedBlob, 'cropped.jpg');

    fetch(`/upload/${ptgbId}/`, {
      method: 'POST',
      headers: {
        'X-CSRFToken': '{{ csrf_token }}'
      },
      body: formData
    })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        {#alert('图片上传并裁剪成功');#}
        location.reload();
      } else {
        alert(data.message || '上传失败');
      }
    })
    .catch(err => {
      console.error(err);
      alert('请求失败');
    });
  }
</script>
</body>
</html>